package com.apache.ius.controller;

import com.apache.cache.util.Validator;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * description: 请求地址进入页面统一action
 * @author xhe 创建时间：2019年03月11日
 */
@Controller
@RequestMapping({"/sendPage/"})
public class SendPageAction  extends BaseAction{
    protected Logger log = Logger.getLogger(getClass());
    private String whiteUrl="/web/user,/admin,";
    private String customLogin = "";//定自义登录页面



    /**
     * 平台管理页面，统一入口方法
     * 请求地址如：sendPage/~/web/user/和sendPage/~/admin/
     */
    @RequestMapping(value = {"/**"})
    @ResponseBody
    public ModelAndView sendPage(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException {
        String requestURI = request.getRequestURI();
        log.info("requrl -->"+requestURI);
        requestURI=requestURI.replaceAll(request.getContextPath()+"/sendPage/","");
        String pageUrl = "/WEB-INF/pages/"+requestURI;
        if("index-ius".equals(requestURI)){
            pageUrl=requestURI;
        }
        log.info("pageUrl-->"+pageUrl);
        Map<String, String> parmMap =  getParameterMap(request);//获取请求参数

        Map<String, Object> defMap = super.getDefaultDataMap(request);//获取freemark模板所需变量

//        log.info("parmMap-->"+parmMap);
        //request.getRequestDispatcher(pageUrl+".jsp").forward(request,response);
        ModelAndView model = new ModelAndView();
        model.addAllObjects(parmMap);//填充参数
        model.addAllObjects(defMap);//填充参数
        model.setViewName(pageUrl);//指定跳转页面地址，根目录=配置文件spring.mvc.view.prefix值
        return model;
    }

    /**
     * description: 生成表单防重复提交令牌
     */
    @RequestMapping(value = "/token", method = RequestMethod.GET)
    public void token(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String uuid = setToken(request);
        this.outputJson(uuid, response, request.getParameter("callback"));
    }
    private String setToken(HttpServletRequest request) {
        if (Validator.isNotNull(request.getParameter("token"))) {
            HttpSession session = request.getSession(true);
            String uuid = UUID.randomUUID().toString();
            if (null != session)
                session.setAttribute("formToken", uuid);
            return uuid;
        }
        return "";
    }

}
